package com.hutu;

public class ReverseWords {

    /**
     * 151. 翻转字符串里的单词 https://leetcode-cn.com/problems/reverse-words-in-a-string/
     * 翻转字符串单词  "hello world" -> "world hello"
     */
    public static String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }
        s = s.trim();
        char[] chars = s.toCharArray();
        StringBuilder stringBuilder = new StringBuilder(chars.length);
        int start = -1;
        int end = -1;
        for (int i = chars.length - 1; i >= 0; i--) {

            if (i == (chars.length - 1)) {
                end = i + 1;
            } else if (chars[i] == ' ' && chars[i - 1] != ' ') {
                end = i;
            }
            if (i == 0) {
                start = i;
            } else if (chars[i] != ' ' && chars[i - 1] == ' ') {
                start = i;
            }

            if (start != -1 && end != -1) {
                stringBuilder.append(s, start, end).append(" ");
                start = -1;
                end = -1;
            }
        }
        return stringBuilder.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("F R  I   E    N     D      S      "));
    }
}
